import SwiftUI

struct ExpenseCategories {
    static let all = ["Food", "Transport", "Shopping", "Bills", "Travel", "Other"]
}

struct AddBudgetView: View {
    @Environment(\.dismiss) private var dismiss

    @State private var category: String = ExpenseCategories.all.first!
    @State private var limit: String = ""
    @State private var initialSpent: String = ""

    var onSave: (Budget) -> Void

    var body: some View {
        NavigationView {
            Form {
                Section(header: Text("Category")) {
                    Picker("Category", selection: $category) {
                        ForEach(ExpenseCategories.all, id: \.self) { cat in
                            Text(cat)
                        }
                    }
                }

                Section(header: Text("Limit")) {
                    TextField("Limit ($)", text: $limit)
                        .keyboardType(.decimalPad)
                }

                Section(header: Text("Already Spent (optional)")) {
                    TextField("Already Spent", text: $initialSpent)
                        .keyboardType(.decimalPad)
                }

                Section {
                    Button("Save Budget") {
                        guard let limitValue = Double(limit) else { return }

                        var expenses: [Expense] = []

                        if let spentValue = Double(initialSpent), spentValue > 0 {
                            expenses.append(
                                Expense(
                                    id: UUID(),
                                    establishment: "Initial Spent",
                                    amount: spentValue,
                                    category: category,
                                    note: "Pre-existing spending"
                                )
                            )
                        }

                        let newBudget = Budget(
                            id: UUID(),
                            category: category,
                            limit: limitValue,
                            expenses: expenses
                        )

                        onSave(newBudget)
                        dismiss()
                    }
                }
            }
            .navigationTitle("New Budget")
        }
    }
}
